"use client";
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Select,
  Table,
  Tree,
  Modal,
  Switch,
  Checkbox,
  Card,
  Divider,
  Tag,
  Space,
} from "antd";
import { Pagination } from "@/utils/db/dbTools";
import React, { useEffect, useState, useRef } from "react";
import { sysRoleTableColumns } from "./tools";
import {
  system,
} from "@/forent-api/api";
import { App } from "antd";
import type { TableProps, FormInstance } from 'antd';

const { Option } = Select;

interface RoleType {
  id: number;
  key: React.Key;
  role_name: string;
  role_key: string;
  status: number;
  description: string;
  permissions: number[];
}

interface PermissionType {
  value: number;
  label: string;
  description: string;
}

const SystemRbacContent: React.FC = () => {
  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const { message, modal, notification } = App.useApp();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [roleModelTitle, setRoleModelTitle] = useState("添加角色");
  const [form] = Form.useForm();
  const [roleTableData, setRoleTableData] = useState<RoleType[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<number[]>([]);
  const [permissionOptions, setPermissionOptions] = useState<PermissionType[]>([]);
  const searchFormRef = useRef<FormInstance>(null);

  /**
   * 确认
   */
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const data = {
        ...values,
        status: values.status ? 1 : 0,
        permissions: selectedPermissions,
        description: values.description || "",
      };

      if (form.getFieldValue("action") == "add") {
        await system.addRole(data);
        setIsModalVisible(false);
        form.resetFields();
        setSelectedPermissions([]);
        getRoleListAction();
      } else {
        data.id = form.getFieldValue("key");
        await system.updateRole(data);
        setIsModalVisible(false);
        form.resetFields();
        setSelectedPermissions([]);
        getRoleListAction();
      }
    } catch (error) {
      console.error("操作失败:", error);
      message.error("操作失败，请重试");
    }
  };

  /**
   * 取消
   */
  const handleCancel = () => {
    form.resetFields();
    setSelectedPermissions([]);
    setIsModalVisible(false);
  };

  useEffect(() => {
    getRoleListAction();
  }, [pagination.current]);

  /**
   * 获取角色列表
   */
  const getRoleListAction = async (data?: any) => {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
    };

    try {
      const res = await system.getRoleList(params);
      if (res.data) {
        setRoleTableData(res.data.data.map((item: any) => ({ ...item, key: item.id })));
        setPagination((prev) => ({
          ...prev,
          total: res.data.total || 0,
          current: res.data.page || 1,
        }));
      }
    } catch (error) {
      message.error("获取角色列表失败");
    }
  };

  /**
   * 切换table的页码
   */
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    setPagination((prev: any) => ({ ...prev, current: pagination.current }));
  };

  /**
   * 新增角色
   */
  const addDict = () => {
    setRoleModelTitle("添加角色");
    showDictModal("add");
  };

  // 显示角色弹窗
  const showDictModal = (action: string) => {
    form?.setFieldsValue({ action }); // 设置当前操作类型
    setIsModalVisible(true);
    // 获取权限列表
    system.getPermissionList().then((res: any) => {
      if (res.code === 200) {
        setPermissionOptions(res.data || []);
      }
    });
  };

  /**
   * 编辑角色
   * @param action
   * @param record
   */
  const onEditRole = (action: string, record: any) => {
    setRoleModelTitle("编辑角色");
    showDictModal(action);

    form?.setFieldsValue({
      ...record,
      action,
      key: record.id,
      status: record.status === 1,
      description: record.description || "",
    });
    setSelectedPermissions(record.permissions || []);
  };

  /**
   * 删除角色
   * @param record
   */
  const onDeleteRole = (record: any) => {
    modal.confirm({
      title: "提示",
      content: "确定要删除该角色配置吗？",
      onOk: () => {
        return system.deleteRole({ id: record.id }).then((res: any) => {
          getRoleListAction();
        });
      },
    });
  };

  const handleSearch = (values: any) => {
    setPagination((prev) => ({ ...prev, current: 1 }));
    getRoleListAction(values);
  };

  const columns: TableProps<RoleType>['columns'] = [
    { title: '角色名称', dataIndex: 'role_name', key: 'role_name' },
    { title: '角色标识', dataIndex: 'role_key', key: 'role_key' },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    { title: '描述', dataIndex: 'description', key: 'description' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => onEditRole('edit', record)}>编辑</a>
          <a onClick={() => onDeleteRole(record)}>删除</a>
        </Space>
      ),
    },
  ];

  return (
    <div className="h-full flex flex-col">
      <div className="flex flex-row justify-between items-center">
        <div>
          <h3 className="text-lg font-semibold">角色权限管理</h3>
        </div>
        <div className="flex gap-2">
          <Button type="primary" onClick={addDict}>
            添加角色
          </Button>
        </div>
      </div>
      <Card className="flex-1 ">
        <Table
          size="small"
          columns={columns}
          dataSource={roleTableData}
          pagination={{
            ...pagination,
            position: ["bottomCenter"],
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          onChange={handleTableChange}
          scroll={{ y: "calc(100vh - 264px)" }}
        />
      </Card>
      <Modal
        title={roleModelTitle}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={800}
      >
        <Form form={form} layout="vertical" initialValues={{ status: true }}>
          <Form.Item name="action" hidden>
            <Input />
          </Form.Item>
          <Form.Item name="key" hidden>
            <Input />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="角色标识"
                name="role_key"
                rules={[{ required: true, message: "请输入角色唯一标识" }]}
              >
                <Input disabled={form.getFieldValue("action") === "edit"} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="角色名称"
                name="role_name"
                rules={[{ required: true, message: "请输入角色名称" }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="status" label="状态" valuePropName="checked">
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          <Form.Item label="描述" name="description">
            <Input.TextArea rows={2} />
          </Form.Item>
          <Form.Item label="权限分配">
            <Checkbox.Group
              style={{ width: "100%" }}
              value={selectedPermissions}
              onChange={(checkedValues) => setSelectedPermissions(checkedValues as number[])}
            >
              <Row>
                {permissionOptions.map(permission => (
                  <Col span={8} key={permission.value}>
                    <Checkbox value={permission.value}>{permission.label}</Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default function SystemRbac() {
  return (
    <App>
      <SystemRbacContent />
    </App>
  );
}
